<!--
 * @Description: 找回密码
-->
<template>
  <div class="choose-company">
    <div class="main-content">
      <div class="main">
        <div class="content">
          <div v-show="selectstau === 1" class="form-list org-list">
            <div class="org-title">
              <div class="sel-te">找回密码</div>
            </div>
            <div class="search">
              <el-form :model="{}">
                <el-form-item :required="true" label="请输入账号：">
                  <el-input v-model="account" placeholder="请输入账号" clearable class="search-input" />
                </el-form-item>
              </el-form>
            </div>
            <div class="company-list">
              <el-button @click="tologin(2)">返回登录</el-button>
              <el-button @click="nextStep(2)">下一步</el-button>
            </div>
          </div>
          <div v-show="selectstau === 2" class="form-list farm-list">
            <div class="org-title">
              <div class="sel-te">
                问题验证
                <span style="font-size:18px">(答对任意二个问题即可找回密码)</span>
              </div>
            </div>
            <div class="organization-list">
              <el-form
                ref="dynamicValidateForm"
                class="dynamicValidateForm"
                :model="dynamicValidateForm"
              >
                <div
                  v-for="item, index in dynamicValidateForm.problemList"
                  :key="item.securityQuestionId"
                  class="sel-company"
                >
                  <el-form-item
                    :required="true"
                    :label="'问题' + (index===0?'一':(index===1?'二':'三')) + '：' + item.question"
                  >
                    <!-- <span>{{ item.question }}</span> -->
                  </el-form-item>
                  <el-form-item
                    :label="''"
                    :prop="'problemList.' + index + '.securityAnswer'"
                    :rules="{
                      required: true, message: '问题' + (index===0?'一':(index===1?'二':'三')) + '答案不能为空', trigger: 'blur'
                    }"
                  >
                    <el-input v-model="item.securityAnswer" clearable />
                  </el-form-item>
                </div>
              </el-form>
            </div>
            <div class="company-list">
              <el-button @click="nextSteps(1)">上一步</el-button>
              <el-button @click="nextStep(3)">下一步</el-button>
            </div>
          </div>
          <div v-show="selectstau === 3" class="form-list farm-list">
            <div class="org-title">
              <div class="sel-te">修改密码</div>
            </div>
            <div class="organization-list pass">
              <el-form ref="formData" :rules="rules" :model="formData">
                <el-form-item label="新密码:" prop="password" class="w100p">
                  <el-input v-model="formData.password" show-password type="password" clearable />
                </el-form-item>
                <el-form-item label="确认密码" prop="newPasswords" class="w100p">
                  <el-input v-model="formData.newPasswords" type="password" autocomplete="off" />
                </el-form-item>
              </el-form>
            </div>
            <div class="company-list">
              <el-button @click="edit()">修改密码</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="logo">
      <img src="~@/assets/login/logo.png" alt />
    </div>
  </div>
</template>
<script>
import userService from "@/api/system-settings/user-manage";
// import { getToken, setToken } from "@/utils/auth";
import { setToken } from "@/utils/auth";
import Axios from "axios";
export default {
  name: "",
  // components: { Header, Footer },
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.formData.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      selectstau: 1, // 1为选择顶级组织结构，2为选择选择农场
      organizationList: [{ companyName: "星光农业有限公司", companyId: 1 }], // 顶级组织结构列表
      activeIdx: "",
      search: "",
      account: "",
      farmList: [{ organizationName: "星光农场", organizationNo: 1 }],
      databaseName: "DB_TDW1_PUBLIC",
      problemList: "",
      dynamicValidateForm: {
        problemList: []
      },
      formData: {},
      rules: {
        password: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur"
          }
        ],
        newPasswords: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          {
            validator: validatePass2,
            trigger: "blur"
          }
        ]
      }
    };
  },
  computed: {
    list() {
      let arr = [...Array(26).keys()].map(i => String.fromCharCode(i + 65));
      arr.unshift("#");
      return arr;
    }
  },
  watch: {},
  created() {
    // 查询农场
    this.getFarmList();
  },
  mounted() {
    // this.tologin()
  },
  methods: {
    tologin() {
      let tr = this.$route.query;
      if (tr.account) {
        let loginForm = {
          account: decodeURIComponent(tr.account),
          password: tr.password
        };
        // this.$store.dispatch("user/login", loginForm)
        this.$router.push({ path: "/login", query: loginForm });
      } else {
        this.$router.push({ path: "/login" });
      }
    },
    async nextStep(e) {
      if (e === 2) {
        if (this.account && this.account !== undefined) {
          const problem = await Axios({
            method: "get",
            url:
              this.$baseurl.webServiceUrl +
              "v3/person/securityQuestion/queryByAccount",
            params: { account: this.account }
          });
          // console.log(problem.data)
          if (problem.data.success) {
            let data = problem.data.data;
            if (data.length > 0) {
              this.dynamicValidateForm.problemList = data;
              this.selectstau = e;
            } else {
              return this.$message.warning("未填写密保问题，请联系管理员修改");
            }
            // this.selectstau = e;
          } else {
            return this.$message.warning(
              problem.data.msg || "账号不存在！！！"
            );
          }
        } else {
          return this.$message.warning("请先输入账号！！！");
        }
      } else if (e === 3) {
        this.$refs["dynamicValidateForm"].validate(async valid => {
          if (valid) {
            // alert('submit!');
            const problem = await Axios({
              method: "POST",
              url:
                this.$baseurl.webServiceUrl +
                "v3/person/securityQuestion/verification",
              data: {
                securityQuestionList: this.dynamicValidateForm.problemList
              }
            });
            if (problem.data.success) {
              let data = problem.data.data;
              if (data) {
                this.selectstau = e;
              } else {
                return this.$message.warning("答案验证失败！！！");
              }
            } else {
              return this.$message.warning(
                problem.data.msg || "问题验证失败！！！"
              );
            }
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      }
    },
    nextSteps(e) {
      this.selectstau = e;
    },
    // 获取顶级组织结构id
    getFarmList() {
      // 获取顶级组织结构id,
      userService.organizationTop().then(res => {
        this.organizationList = res.data;
      });
    },
    // 点击组织结构触发方法
    goToselectFarm(e) {
      //  this.$router.push({ name: "EnvironmentalDataMonitoring" });
      userService.farmListbyOrganizationId(e).then(res => {
        this.farmList = res.data;
        if (this.farmList.length > 0) {
          this.$message.success("选择顶级组织结构成功！");
          this.selectstau = 2;
        } else {
          this.$message.warning("选择顶级组织结构失败！");
        }
      });
    },
    // 点击农场
    goToTheFarm(organizationNo) {
      setToken("organizationNo", organizationNo);
      this.$router.push({ name: "EnvironmentalDataMonitoring" });
    },
    edit() {
      this.$refs["formData"].validate(async valid => {
        if (valid) {
          // alert('submit!');
          const problem = await Axios({
            method: "POST",
            url: this.$baseurl.webServiceUrl + "v3/person/user/editPassword",
            data: { ...this.formData, username: this.account }
          });
          if (problem.data.success) {
            // let data = problem.data.data
            // if (data) {
            // this.selectstau = e;
            setTimeout(() => {
              this.$router.push({ path: "/login" });
            }, 100);

            // } else {
            //   return this.$message.warning('答案验证失败！！！')
            // }
          } else {
            return this.$message.warning(
              problem.data.msg || "答案修改失败！！！"
            );
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // ---侧边栏abcd选择，然而并没什么用
    changeActiveIdx(idx, item) {
      this.activeIdx = idx;
      this.search = item;
      // console.log(this.search);
    }
  }
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";
@keyframes borderbg {
  from {
    border-radius: 0;
  }
  to {
    background-color: #fff;
    color: #333;
    border-radius: 20px;
  }
}

.logo {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  bottom: 20px;
}
$slidebarWidth: 40px;
::v-deep {
  .el-form {
    width: 100%;
  }
  .el-form-item {
    display: flex;
    flex-direction: column;
    .el-form-item__label {
      color: #6f6f6f;
      font-size: 20px;
      text-align: start;
      margin-bottom: 10px;
    }
  }
}
.dynamicValidateForm {
  margin-bottom: 80px;
}
.choose-company {
  width: 100%;
  height: 100%;
  .main-content {
    display: flex;
    width: 100%;
    height: 100%;
    background: url("~@/assets/login/back.jpg");
    background-size: cover;
    background-repeat: no-repeat;
    font-size: 14px;
    .el-scrollbar {
      background-color: #006988;
      .slidebar {
        width: $slidebarWidth;
        height: 100%;
        // overflow-y: auto;
        .list {
          width: 100%;
          .item {
            width: $slidebarWidth;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            font-size: 16px;
            &:hover {
              animation-name: borderbg;
              animation-iteration-count: 1;
              animation-fill-mode: forwards;
              animation-duration: 0.5s;
            }
          }
          .active {
            font-weight: bold;
            background-color: #fff;
            color: #333;
            border-radius: 20px;
          }
        }
      }
    }

    .main {
      width: 100%;
      .content {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        .form-list {
          background-color: #fff;
          .org-title {
            height: 42px;
            background-color: #2a94fc;
            color: #fff;
            padding-left: 20px;
            font-size: 23px;
            display: flex;
            align-items: center;
            .sel-te {
              padding-left: 10px;
              line-height: 27px;
              height: 27px;
              // border-left: #fff 4px solid;
              color: #fff;
              font-size: 23px;
            }
          }
        }
        .org-list {
          position: relative;
          width: 520px;
          border-radius: 5px;
          box-shadow: 0px 3px 6px 1px rgba(0, 0, 0, 0.51);
          min-height: 350px;
          .search {
            width: 100%;
            min-height: 50px;
            margin-top: 40px;
            margin-bottom: 30px;
            display: flex;
            padding: 10px 40px;
            align-items: center;
            justify-content: center;
            flex-direction: row;
            flex-wrap: wrap;
            color: #fff;
            font-size: 20px;
            .search-input {
              outline: none;
              border: #fff 2px solid;
              font-size: 18px;
              width: 100%;
              height: 40px;
            }
            .search-button {
              color: #fff;
              width: 80px;
              height: 40px;
              line-height: 40px;
              font-size: 18px;
              text-align: center;
              background-color: #7fd354;
              border-top-left-radius: 0px;
              border-top-right-radius: 2px;
              border-bottom-right-radius: 2px;
              border-bottom-left-radius: 0px;
              cursor: pointer;
            }
          }
          .company-list {
            overflow: auto;
            margin-left: auto;
            margin-right: auto;
            display: flex;
            flex-direction: row;
            flex-wrap: wrap;
            position: absolute;
            bottom: 55px;
            right: 50%;
            transform: translateX(50%);
          }
          .sel-company {
            width: 270px;
            height: 46px;
            margin: 0px 30px 30px 30px;
            white-space: nowrap;
            cursor: pointer;
            background-color: transparent;
            border: #fff 1px solid;
            line-height: 46px;
            text-align: center;
            color: #fff;
          }
          .sel-company:hover {
            background-color: #fff;
            color: rgba(0, 81, 81, 1);
          }
        }
        .farm-list {
          width: 520px;
          min-height: 350px;
          background-color: #fff;
          position: relative;
          .company-list {
            overflow: auto;
            margin-left: auto;
            margin-right: auto;
            display: flex;
            flex-direction: row;
            flex-wrap: wrap;
            position: absolute;
            bottom: 31px;
            right: 50%;
            transform: translateX(50%);
          }
          .organization-list {
            width: 100%;
            // height: 228px;
            padding: 10px 40px;
            // margin-top: 40px;
            // padding-left: 10px;
            overflow: auto;
            margin-left: auto;
            margin-right: auto;
            display: flex;
            flex-direction: row;
            flex-wrap: wrap;
          }
          .sel-organization {
            width: 270px;
            height: 46px;
            margin: 0px 30px 30px 30px;
            white-space: nowrap;
            cursor: pointer;
            background-color: transparent;
            border: #fff 1px solid;
            line-height: 46px;
            text-align: center;
            color: #fff;
          }
          .sel-organization:hover {
            background-color: #fff;
            color: rgba(0, 81, 81, 1);
          }
        }
      }
    }
  }
}
</style>
<style lang="scss">
.el-scrollbar__wrap {
  overflow-x: hidden;
}
.is-horizontal {
  display: none;
}
</style>
